package com.dyj.ads

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.{DataFrame, SparkSession}

object ads_e_mz_au5800_zdhs {
  def main(args: Array[String]): Unit = {
    val ds: String = args(0)

    val sparkSession: SparkSession = SparkSession.builder()
      .appName("胆红素指标统计")
      .enableHiveSupport()
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()

    import sparkSession.implicits._
    import org.apache.spark.sql.functions._

    sparkSession.sql("use bigdata03_dws")

    val zdhsDF: DataFrame = sparkSession.sql(
      s"""
        |select
        |baoGaoBianHao,
        |zongDanHongSu,
        |baoGaoRiQi,
        |zdhs_max,
        |zdhs_min,
        |zdhs_avg
        |from
        |bigdata03_dws.dws_e_mz_au5800shenghua
        |where
        |ds='${ds}'
        |""".stripMargin)

    zdhsDF
      .withColumn("number", count($"baoGaoBianHao") over Window.partitionBy($"baoGaoBianHao"))
      .withColumn("e_fc", ($"zongDanHongSu" - $"zdhs_avg") * ($"zongDanHongSu" - $"zdhs_avg"))
      .withColumn("a_fc", sum($"e_fc").over())
      .withColumn("zdhs_fc", $"a_fc" / $"number")
      .withColumn("zdhs_bzc", sqrt($"zdhs_fc"))
      .withColumn("zdhs_ycgs", sum(when($"zongDanHongSu" < 1.71 or($"zongDanHongSu" > 21), 1)).over())
      .select($"baoGaoBianHao", $"zongDanHongSu", $"baoGaoRiQi", $"zdhs_max", $"zdhs_min", $"zdhs_avg", $"zdhs_fc", $"zdhs_bzc", $"zdhs_ycgs")
      .write
      .format("csv")
      .save("/daas/motl/bigdata03/ads/ads_e_mz_au5800_zdhs/ds=" + ds)
  }

}
